using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.VisualBasic;

namespace Lincolnwood.Foundation.Scheduling
{
    public sealed class DailyRecurrencePattern : RecurrencePattern
    {

        private DailyRecurrencePattern(): base()
        { }

        public DailyRecurrencePattern(DateTime endDate, int dayInterval)
            : base(endDate, dayInterval)
        {
        }

        public override DateTime FindClosestRecurrenceDate(RecurrableEventDefinition eventContext, DateTime expandBegin)
        {
            // Get the difference in days between the start of the expansion period and the start of the recurring event period.
            TimeSpan eventDuration = eventContext.EndTime - eventContext.StartTime;

            Double dateDifferenceDays = expandBegin.Subtract(eventContext.StartTime + eventDuration).TotalDays; // DateAndTime.DateDiff(DateInterval.Day, this.StartDate, expandBegin, FirstDayOfWeek.Sunday, FirstWeekOfYear.Jan1);
            
            // Compute how many recurrence intervals fall in the difference.
            // and round the result up to the closest whole number.
            Double exactIntervals = dateDifferenceDays / (Double)this.Interval;
            int closestWholeIntervals = (int)Math.Ceiling(exactIntervals);

            // Multiply the whole number by the interval
            // and add the product to the start of the recurring event.
            // This computes the closest event to the start of our expansion period.
            DateTime closestRecurrence = eventContext.StartTime.AddDays(this.Interval * closestWholeIntervals);

            if (closestRecurrence < eventContext.StartTime)
                closestRecurrence = eventContext.StartTime;

            return closestRecurrence;
        }

        public override DateTime GetNextRecurrenceDate(DateTime baseDate)
        {
            return baseDate.AddDays(this.Interval);
        }        
    }
}